package net.goutalk.glcs.module.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.model.result.R;
import net.goutalk.glcs.common.page.ConventPage;
import net.goutalk.glcs.common.page.PageOutput;
import net.goutalk.glcs.common.utils.UploadUtil;
import net.goutalk.glcs.common.utils.VoToColumnUtil;
import net.goutalk.glcs.config.OSSConfig;
import net.goutalk.glcs.module.organization.entity.User;
import net.goutalk.glcs.module.system.dto.FileListDto;
import net.goutalk.glcs.module.system.dto.FilePageDto;
import net.goutalk.glcs.module.system.entity.File;
import net.goutalk.glcs.module.system.service.IFileService;
import net.goutalk.glcs.module.system.vo.FileListVo;
import net.goutalk.glcs.module.system.vo.FileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 文件关联关系表 前端控制器
 * </p>
 *
 * @author tanyujie
 * @since 2022-03-08
 */
@RestController
@RequestMapping(GlobalConstant.SYSTEM_MODULE_PREFIX + "/file")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/file", tags = "文件")
@AllArgsConstructor
public class FileController {
    private IFileService fileService;

    private OSSConfig ossConfig;


    @GetMapping("/info")
    @ApiOperation(value = "根据文件Id获取单个文件数据")
    public R info(@RequestParam String id) {
        return R.ok(fileService.getById(id));
    }

    @GetMapping
    @ApiOperation(value = "查询文件列表（不分页）")
    public R list(@Valid FileListDto dto) {

        List<FileListVo> list = fileService.selectJoinList(FileListVo.class, MPJWrappers.<File>lambdaJoin()
                .like(StrUtil.isNotBlank(dto.getFileName()), File::getFileName, dto.getFileName())
                .eq(ObjectUtil.isNotNull(dto.getFolderId()), File::getFolderId, dto.getFolderId())
                .eq(StrUtil.isNotBlank(dto.getProcessId()), File::getProcessId, dto.getProcessId())
                .select(File::getId)
                .select(File.class, x -> VoToColumnUtil.fieldsToColumns(FileListVo.class).contains(x.getProperty()))
                .selectAs(User::getName, FileListVo::getCreateUserName)
                .leftJoin(User.class, User::getId, File::getCreateUserId)
                .last(StrUtil.isNotBlank(dto.getField()), GlobalConstant.ORDER_BY + StringPool.SPACE + StrUtil.toUnderlineCase(dto.getField()) + StringPool.SPACE + ConventPage.getOrder(dto.getOrder())));

        return R.ok(list);
    }

    @GetMapping("/page")
    @ApiOperation(value = "查询文件列表(分页)")
    public R page(@Valid FilePageDto dto) {
        LambdaQueryWrapper<File> wrapper = Wrappers.<File>query().lambda()
                .like(StrUtil.isNotBlank(dto.getFileName()), File::getFileName, dto.getFileName())
                .eq(ObjectUtil.isNotNull(dto.getFolderId()), File::getFolderId, dto.getFolderId())
                .eq(StrUtil.isNotBlank(dto.getProcessId()), File::getProcessId, dto.getProcessId());

        IPage<File> page = fileService.page(ConventPage.getPage(dto), wrapper);
        PageOutput<File> pageOutput = ConventPage.getPageOutput(page, File.class);
        return R.ok(pageOutput);
    }

    @DeleteMapping
    @ApiOperation(value = "删除文件(可批量)")
    public R delete(@RequestBody List<Long> ids) {

        return R.ok(fileService.removeBatchByIds(ids));
    }

    @DeleteMapping("/delete-single")
    @ApiOperation(value = "删除组件 删除单个文件")
    public R delete(@RequestBody Long id) {

        File deleteFile = fileService.getById(id);
        //找到没有被删除的文件
        List<File> list = fileService.list(Wrappers.lambdaQuery(File.class).eq(File::getFolderId, deleteFile.getFolderId()).ne(File::getId, id));

        //如果删除的是最后一个文件  就返回空值
        if(list.size() > 0){
            Long newfolderId = IdWorker.getId();

            for (File newFile : list) {
                newFile.setId(null);
                newFile.setFolderId(newfolderId);
            }
            List<File> insertFile = new ArrayList<>(list);

            fileService.saveBatch(insertFile);

            return R.ok(newfolderId);

        }
        else {
            return R.ok(StringPool.EMPTY);
        }

    }

    @PostMapping
    @ApiOperation(value = "单文件上传")
    public R uploadFile(@RequestParam(value = "file", required = true) MultipartFile multipartFile) throws Exception {
        Long folderId = IdWorker.getId();
        Long fileId = IdWorker.getId();
        File file = uploadFile(multipartFile, folderId, fileId);
        return R.ok(file.getFileUrl());
    }

    @PostMapping("/folder")
    @ApiOperation(value = "单文件上传")
    public R uploadFileToFolder(@RequestParam Long folderId, @RequestParam MultipartFile multipartFile) throws Exception {
        Long fileId = IdWorker.getId();
        File file = uploadFile(multipartFile, folderId, fileId);
        return R.ok(file.getFileUrl());
    }


    @PostMapping("/multiple-file-upload")
    @ApiOperation(value = "多文件上传")
    public R uploadFiles(@RequestParam(value = "file") MultipartFile[] multipartFiles ) throws Exception {
        List<String> urlList = new ArrayList<>();
        if (multipartFiles != null && multipartFiles.length > 0) {
            Long folderId = IdWorker.getId();
            for (MultipartFile multipartFile : multipartFiles) {
                Long fileId = IdWorker.getId();
                File file = uploadFile(multipartFile, folderId, fileId);
                urlList.add(file.getFileUrl());
            }

        }
        return R.ok(urlList);
    }

    @PostMapping("/multiple-file-upload/folder")
    @ApiOperation(value = "多文件上传")
    @Transactional
    public R uploadFilesToFolder(@RequestParam(required = false) Long folderId, @RequestParam(value = "file") MultipartFile[] multipartFiles) throws Exception {
        List<FileVo> fileVoList = new ArrayList<>();
        if (multipartFiles != null && multipartFiles.length > 0) {
            for (MultipartFile multipartFile : multipartFiles) {
                Long fileId = IdWorker.getId();
                if (folderId == null) {
                    folderId = IdWorker.getId();
                }
                File file = uploadFile(multipartFile, folderId, fileId);
                fileVoList.add(BeanUtil.toBean(file, FileVo.class));
            }
        }
        return R.ok(fileVoList);
    }

    private File uploadFile(MultipartFile multipartFile, Long folderId, Long fileId) throws Exception {
        String filename = multipartFile.getOriginalFilename();
        String suffix = StringUtils.substringAfterLast(filename, StringPool.DOT);
        //保存到云服务器
        String filePath = UploadUtil.uploadFile(multipartFile);

        File file = new File();
        file.setId(fileId);
        file.setFolderId(folderId);
        file.setFileName(filename);
        file.setFileUrl(filePath);
        file.setFileSize(multipartFile.getSize());
        file.setFileSuffiex(StringPool.DOT + suffix);
        file.setFileType(suffix);
        fileService.save(file);
        return file;
    }
}
